package com.itasura.guava.FunctionalProgramming;

import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.collect.Lists;
import com.itasura.guava.BasicGuavaUtilities.User;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author sailor wang
 * @date 2018/10/19 下午2:17
 * @description
 */
@Slf4j
public class FunctionsTest {

    //以对象为入参，以对象的 toString 方法的返回值为返回值
    @Test
    public void toStringFunctionTest() {
        Function<Object, String> stringFunctions = Functions.toStringFunction();
        User user = new User();
        user.setName("sailor");
        user.setAge(28);
        String str = stringFunctions.apply(user);
        log.info("str -> {}", str);
    }

    //以对象为入参，返回对象本身
    @Test
    public void forMapTest() {
        Map<String, String> map = new HashMap<String, String>() {
            {
                put("hello", "how are u?");
                put("fine", "thank you!");
                put("and you", null);
            }
        };
        Function<String, String> mapFun = Functions.forMap(map);
        String val1 = mapFun.apply("hello");//感觉有点傻
        log.info("hello -> {}", val1);
        String val2 = mapFun.apply("and you");
        log.info("and you -> {}", val2);
    }

    @Test
    public void composeTest() {
        // 过关卡
        Function<User, Boolean> goodManFun = new Function<User, Boolean>() {
            @Override
            public Boolean apply(User user) {
                return user.getName().equalsIgnoreCase("zhangsan");//张三是良民
            }
        };


        // 打标签
        Function<String, User> doTagFun = new Function<String, User>() {
            @Override
            public User apply(String s) {
                User user = new User();
                user.setName(s);
                return user;
            }
        };

        Function<String, Boolean> barrierFun = Functions.compose(goodManFun, doTagFun);
        User u1 = new User();
        u1.setName("zhangsan");
        User u2 = new User();
        u2.setName("lisi");
        User u3 = new User();
        u3.setName("wangwu");

        List<User> persons = Lists.newArrayList(u1, u2, u3);

        persons.forEach(user -> {
            Boolean result = barrierFun.apply(user.getName());
            if (result) {
                log.info("{} 良民大大滴！", user.getName());
            } else {
                log.info("{} 大大滴坏！", user.getName());
            }
        });


    }


}